package com.heeexy.example.service;

import com.alibaba.fastjson.JSONObject;
import com.heeexy.example.dao.FilesDao;
import com.heeexy.example.dto.FilesEntity;
import com.heeexy.example.util.CommonUtil;
import com.heeexy.example.util.FileUtil;
import com.heeexy.example.util.constants.ErrorEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author MyPC
 * @Date 2022/3/31 13:52
 * @description：
 * @Version 1.0
 */
@Slf4j
@Service
public class FilesService {

    private FilesDao filesDao;

    @Autowired
    public void setFilesDao(FilesDao filesDao) {
        this.filesDao = filesDao;
    }

    /**
     * 添加素材资源
     * @param uid file
     * @return
     */
    public JSONObject addFiles(MultipartFile file,String uid){
        try{
            //获取存储路径
            String realPath= ResourceUtils.getURL("classpath:").getPath()+"/static/images";
            File dateDir = FileUtil.mkdirsPath(realPath);
            FilesEntity filesEntity = new FilesEntity();

            filesEntity.setSize(file.getSize());
            filesEntity.setPath(dateDir.getPath());
            filesEntity.setDowncounts("");
            filesEntity.setType(file.getContentType());
            filesEntity.setOldFileName(file.getOriginalFilename());
            filesEntity.setNewFileName(FileUtil.newFileName(file));
//            filesEntity.setUId(uid);
            file.getOriginalFilename();

            //获取原文件名
            file.getOriginalFilename();
            //根据日期生成目录

            file.transferTo(new File(dateDir,filesEntity.getNewFileName()));
            //生成文件存储路径

            //获取文件大小
            //获取所属作者ID
            //资源标签
            //所属场馆
            filesDao.saveFile(uid);
        }catch (IOException e){
            log.error("文件传输异常：");
            return CommonUtil.errorJson(ErrorEnum.E_400);
        }

        return CommonUtil.successJson();
    }
}
